package src.com.java.dtgh.twoDay;

import java.util.Arrays;

public class demo4 {

    public int lastStoneWeightII(int[] stones) {

        if(stones.length == 1){
            return stones[0];
        }
        if(stones.length == 2){
            return Math.abs(stones[0] - stones[1]);
        }
        int sum = 0;
        for (int stone : stones) {
            sum += stone;
        }
        int target = sum >> 1;
        int[] dp = new int[target + 1];

        Arrays.fill(dp, 0);
        for(int i = 0;i < stones.length;i++){
            for(int j = target;j >= stones[i];j--){
                dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]);
            }
        }
        return sum - dp[target] * 2;
    }
}
